A sequence point in imperative programming defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. They are often mentioned in reference to C and C++, because the result of some expressions can depend on the order of evaluation of their subexpressions. Adding one or more sequence points is one method of ensuring a consistent result, because this restricts the possible orders of evaluation.
Consider two functions f()
and g()
. In C and C++, the +
operator is not associated with a sequence point, and therefore in the expression f()+g()
it is possible that either f()
or g()
will be executed first. The comma operator introduces a sequence point, and therefore in the code f(),g()
the order of evaluation is defined: first f()
is called, and then g()
is called.
Sequence points also come into play when the same variable is modified more than once within a single expression. An often-cited example is the C expression i=i++
, which apparently both assigns i
its previous value and increments i
. The final value of i
is ambiguous, because, depending on the order of expression evaluation, the increment may occur before, after, or interleaved with the assignment. The definition of a particular language might specify one of the possible behaviors or simply say the behavior is undefined. In C and C++, evaluating such an expression yields undefined behavior.[1]
In C[2] and C++,[3] sequence points occur in the following places. (In C++, overloaded operators act like functions, and thus operators that have been overloaded introduce sequence points in the same way as function calls.)
*p++ != 0 && *q++ != 0
, all side effects of the sub-expression *p++ != 0
are completed before any attempt to access q
.a = (*p++) ? (*p++) : 0
there is a sequence point after the first *p++
, meaning it has already been incremented by the time the second instance is executed.a=b;
), return statements, the controlling expressions of if
, switch
, while
, or do
-while
statements, and all three expressions in a for
statement.f(i++) + g(j++) + h(k++)
, f
is called with a parameter of the original value of i
, but i
is incremented before entering the body of f
. Similarly, j
and k
are updated before entering g
and h
respectively. However, it is not specified in which order f()
, g()
, h()
are executed, nor in which order i
, j
, k
are incremented. Variables j
and k
in the body of f
may or may not have been already incremented. Note that a function call f(a,b,c)
is not a use of the comma operator and the order of evaluation for a
, b
, and c
is unspecified.5
in the declaration int a = 5;
.a++
in int x = a++, y = a++
[5].